import COSSDK from 'cos-js-sdk-v5'
import Compressor from 'compressorjs';
import { Toast } from "vant";
import globalfunc from './common.js';
import axios from "@/api/api.js";
// 注册 cos

const cos = new COSSDK({
    getAuthorization: function (options, callback) {
        axios.get('public/getCosCredential').then((res)=>{
            if(res.errno==0)
            {
                var credentials = res.data.credentials;
                callback({
                    TmpSecretId: credentials.tmpSecretId,
                    TmpSecretKey: credentials.tmpSecretKey,
                    XCosSecurityToken: credentials.sessionToken,
                    // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                    StartTime: res.data.startTime, // 时间戳，单位秒，如：1580000000
                    ExpiredTime: res.data.expiredTime, // 时间戳，单位秒，如：1580000900
                });
            }else{
                Toast({
                  message: "上传图像失败,原因:"+res.errmsg,
                  type: 'fail',
                  duration: 2000
                })
                return console.error('credentials invalid');
            }
        }).catch((err)=>{
            Toast({
              message: "上传图像失败,cos未能成功初始化",
              type: 'fail',
              duration: 2000
            })
            return console.error('credentials invalid');
        })
    }
});

const Bucket='meow-1253722568';
const Region='ap-chengdu';


const CosUpload = function (file,folder,callback){
    var size=file.size;
    var mintype=file.type;
    var type = mintype.indexOf('/')>0?mintype.split('/')[1]:mintype;
    var name = file.name;
    if(!name)
    {
        name= globalfunc.randomKey(false,6)+"."+type;
    }else{
       name= globalfunc.randomKey(false,6)+"_"+name;
    }
    var timestamp = Date.parse(new Date()) / 1000;
    var postkey=folder+'/'+globalfunc.timetostr(timestamp,3)+'/'+name;
    new Compressor(file, {
        quality: 1,
        maxWidth:500,
        success(result) {
            cos.putObject({
                Bucket: Bucket, /* 必须 */
                Region: Region,    /* 必须 */
                Key: postkey, //文件夹名字加文件名,文件夹不存在就会自动创建
                Body: result, // 上传文件对象
            }, function(err, data) {
                if(err==null)
                {
                    var url='https://'+data.Location;
                    var resdata={
                        key:postkey,
                        url:url
                    }
                    typeof callback == "function"&&callback(true,resdata);
                }else{
                    typeof callback == "function"&&callback(false);
                }
            });
        },
        error(err) {
          Toast({
            message: "图像压缩失败,无法完成发送",
            type: 'fail',
            duration: 2000
          })
          typeof callback == "function"&&callback(false);
        }
    });
}
const CosDelete = function (key,callback) {
    cos.deleteObject({
       Bucket: Bucket, /* 必须 */
       Region: Region,     /* 存储桶所在地域，必须字段 */
       Key: key        /* 必须 */
    }, function(err, data) {
       if(!err)
       {
           if(data.statusCode==204||data.statusCode==200)
           {
               callback(true);
           }else{
               callback(false);
           }
       }else{
           callback(false);
       }
    });
}
export { CosUpload, CosDelete };